<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

class SpiderrobotWorkSum extends Backend
{
    /**
     * LiveStreamer模型对象
     * @var \app\admin\model\LiveStreamer
     */
    protected $model = null;

    //protected $agentstaff = null;

    protected $admin = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SpiderrobotWorkSum();

        //$this->agentstaff = new \app\admin\model\agent\Agentstaff;

        $this->admin = new Admin();
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $admin = $this->admin->where([
                'status' => 'normal'
            ])->select();

            $list = [];
            foreach ($admin as $item => $value) {
                $list[$value->username] = $value->username;
            }

            $this->assignconfig("adminUserList", $list);
            $this->assign("loginUserId", $this->auth->username);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
//            $agentstaffList = $this->agentstaff->where([
//                'status' => 1
//            ])->select();

            $admin = $this->admin->where([
                'status' => 'normal'
            ])->select();

            $list = [];
            foreach ($admin as $item => $value) {
                $list[$value->username] = $value->username;
            }

            $Robottype = [
                1 => '爬虫机器人',
                2 => '经纪机器人'
            ];

            $this->assign("loginUserId", $this->auth->id);
            $this->assign("agentstaffList", $list);
            $this->assign("robotType", $Robottype);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            if (strlen($params['robotUser']) <= 0 || strlen($params['robotUser']) > 64) {
                $this->error("机器人账号长度限制为0-64个字符");
            }
            $param = "'" . $params['agentID'] . "'," . $params['Robottype'] . ",'" . $params['robotUser'] . "',
            '" . $params['robotUser'] . "', '" . $params['region'] . "',null,0,0,0,0,@_res";
            Db::query("call robotuser_add($param)");
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function spidersetting($ids)
    {
        if (false === $this->request->isPost()) {
            $data = Db::table("spiderrobot_set")->where([
                'robotUser' => $ids
            ])->find();

            $this->assign('data', $data);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $sql = "call spiderrobot_param_set('".$ids."', ".$params['videoRefresh'].", ".$params['videoMaxTask'].", "
                .$params['videoMaxLikes'].", 0, ".$params['roomInterval'].", ".$params['roomMaxTask'].", "
                .$params['roomIsGetCostInfo'].", ".$params['roomIsGetCostUser'].", ".$params['roomIsGetBox'].", "
                .$params['roomIsCall'].", ".$params['roomIsHeat'].", @_res)";
            Db::query($sql);
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function boxdetail($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            $this->assignconfig("robotnickname", request()->get("robotnickname"));
            return $this->view->fetch();
        }

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = Db::table("spiderrobot_box_diamands_log")
            ->where($where)
            ->where([
                'robotUser' => request()->get("robotnickname")
            ])
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
}